<template>
  <span v-if="props.showText">{{ message }}</span>
  <el-radio-group
    v-else
    v-model="dicSelect" 
    @change="handleChange"
  >
    <el-radio
      v-for="item in options" 
      :key="item.key"
      :label="item.key"
    >{{item.value}}</el-radio>
  </el-radio-group>
</template>

<script setup>
import {ref, watch, onMounted, onUnmounted, nextTick} from 'vue';
import {useDictionaryStore} from '@/pinia/modules/dictionary';
import {useFormItem} from 'element-plus';
import {emitter} from "@/utils/bus";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  dicCode: String,
  showText: Boolean,
});

const dictionaryStore = useDictionaryStore();
const options = ref([]);
const message = ref('');
const dicSelect = ref('');
const formItem = useFormItem();

const handleChange = () => {
  let key = '', value = '';
  if (dicSelect.value && options.value) {
    key = dicSelect.value;
    options.value.forEach(item => {
      if (item.key === key) {
        value = item.value;
      }
    });
  }

  emit('update:modelValue', key, value);
  emit('change', key, value);

  if (formItem && formItem.formItem) {
    nextTick(() => {
      formItem.formItem.validate('change');
    });
  }
};

const loadDicAndShow = async(dicCode) => {
  if ((dicCode || '') === '') {
    options.value = [];
  } else {
    options.value = await dictionaryStore.getDictionary(dicCode);
  }
  calcValue();
};

const calcValue = () => {
  if (options.value == null || options.value.length <= 0) {
    message.value = props.modelValue;
  } else {
    if (props.showText) {
      let optionValues = '';
      let values = (props.modelValue || '').split(',');
      values.forEach(value => {
        let option = options.value.filter(item => item.key === value + '')
        if (option.length > 0) {
          if (optionValues !== '') {
            optionValues += ',';
          }
          optionValues += option[0].value;
        }
      });
      message.value = optionValues;
    } else {
      let option = options.value.filter(item => item.key === dicSelect.value)
      if (option.length > 0) {
        message.value = option[0].value;
      } else {
        message.value = props.modelValue;
      }
    }
  }
};

const init = (data) => {
  dicSelect.value = data.modelValue || '';
  loadDicAndShow(data.dicCode);

  emitter.off('dictionary.change');
  emitter.on('dictionary.change', () => {
    loadDicAndShow(data.dicCode);
  });
};

watch(() => props, (data) => {
  init(data);
}, {deep: true});

onMounted(() => {
  init(props);
});

onUnmounted(() => {
  emitter.off('dictionary.change');
});
</script>